package com.dxy.shardingjdbc.algorithm;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 告警表分表复核算法
 * @Author dangxianyue
 * @Date 2023/2/8 13:54
 */
public class AlarmSubTableComplexAlgorithm implements ComplexKeysShardingAlgorithm {

    //id列名
    private static final String COLUMN_ID = "id";

    //告警时间列名
    private static final String COLUMN_ALARM_TIME = "alarm_time";

    /**
     * 分表算法逻辑
     *
     * @param availableTargetNames 物理表列表，t_alarm_01、t_alarm_02、...、t_alarm_12
     * @param shardingValue        分片键值，id、alarm_time
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection availableTargetNames, ComplexKeysShardingValue shardingValue) {
        System.out.println("subTable:\navailableTargetNames: " + JSON.toJSONString(availableTargetNames) + "\nshardingValue: " + JSON.toJSONString(shardingValue));

        // 获取id
        Collection ids = (Collection) shardingValue.getColumnNameAndShardingValuesMap().getOrDefault(COLUMN_ID, new ArrayList<>(1));

        // 获取告警时间
        Collection alarmTimes = (Collection) shardingValue.getColumnNameAndShardingValuesMap().getOrDefault(COLUMN_ALARM_TIME, new ArrayList<>(1));

        //整合id、alarm_time
        List<String> list = new ArrayList<>();
        ids.forEach(id -> list.add(id.toString().substring(2,4)));
        alarmTimes.forEach(alarmTime -> list.add(LocalDateTimeUtil.format((LocalDateTime) alarmTime, "MM")));

        List<String> tableList = list.stream()
                .distinct()
                .map(tableSuffix -> shardingValue.getLogicTableName() + "_" + tableSuffix)
                .collect(Collectors.toList());
        System.out.println("tableList: " + JSON.toJSONString(tableList));
        return tableList;
    }

}
